<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Article $article)//这里是laravel的依赖注入方法相当于$article=new Article();
    {
        $articles=$article->all();
        //渲染视图，compact('articles')会将$articles数组化
        return view('articles._list',compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Article $article)
    {
        return view('articles._create', compact('article'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Article $article)
    {
        //Validator验证输入问题
        Validator::make($request->toArray(), [//图片过滤
            'title' => 'required|unique:articles|min:2',
            'content' => 'required',
        ],
            [
                'title.required' => '文章标题不能为空',
                'title.unique' =>'标题不能重复',
                'title.min' =>'标题至少两个字',
                'content.required'  => '内容不能为空',
            ])->validate();
        $article->fill($request->all());//变量填充
        $article->save();//变量存储数据

        return redirect()->route('articles.index');//重定向到index页面
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article)
    {
        return view('articles._edit', compact('article'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {

        Validator::make($request->toArray(), [//过滤请求信息，[name]，[提示]
            'title' => 'required|min:2',
            'content' => 'required',
        ],
            [
                'title.required' => '文章标题不能为空',
                'title.min' =>'标题至少两个字',
                'content.required'  => '内容不能为空',
            ])->validate();
        $article->fill($request->all());//变量填充数据
        $article->save();//变量保存数据

        return redirect()->route('articles.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        $article->delete();//调用默认的delete方法
        return redirect()->route('articles.index');//重定向路由
    }
}
